// Comcom_console_c.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <WinSock2.h>
//Also linked ws2_32.lib under project/properties/linker

/////////////////////////////////////////////////////////////
//Forward declarations
/////
char read_command(); //Returns either '\0' on error or char from stdin
void print_menu(int menu_num); //Prints menu to stdin, menu_num decides which menu
int connect_to_server(); //Connects to the server

/////////////////////////////////////////////////////////////
//DEFINITIONS
/////
#define MENU_MAIN		1
#define MESSAGE_SIZE	1024

/////////////////////////////////////////////////////////////
//MAIN FUNCTION
/////
int _tmain(int argc, _TCHAR* argv[])
{
	//Initialization
	char command = '\0'; //Will use the null char for errors and initialization

	//Initialize Winsock version 2.2
	WSAData wsaData;

	int ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if ( ret != 0){
		//Start up failed!
		printf("WSAStartup failed with error: %d\n", ret);
		return -1; //Error
	}

	//Main loop
	while ( command != 'q' ){
		print_menu(MENU_MAIN);
		command = read_command();

		//only use the tolower() call if command is a valid character
		if (command != '\0'){
			command = tolower(command);
		}

		switch ( command ){
		case 'c':
			//connect to server
			printf("Preparing to connect...\n");

			ret = connect_to_server();

			if ( ret != 0){
				printf("Error from connect_to_server! Error: %d\n", ret);
			}

			break;
		case 'q':
			//Quit
			printf("Goodbye.\n");
			break;
		default:
			printf("Sorry, that was not a valid command.\n");
		}

	}


	//Call WSACleanup
	ret = WSACleanup();
	if ( ret != 0 ){
		printf("Error with WSACleanup! Error: %d\n", WSAGetLastError());
	}

	return 0;
}

/////////////////////////////////////////////////////////////
//Functions
/////

//READ_COMMAND()
char read_command()
{
	// read_command() will read from stdin and is used when wanting a command
	// read_command() will return a /0 (null) character on error
	// otherwise, read_command() will return the character entered by the user
	char command;
	char junk;

	command = fgetc(stdin);

	if ( command == '\n' ){
		printf("Enter something!\n");
		return '\0';
	}

	junk = fgetc(stdin);
	if ( junk != '\n'){
		// The user entered too many characters
		printf("You entered too many characters!\n");
		command = '\0';
		
		while ( junk != '\n' ){
			// Clear out stdin
			junk = fgetc(stdin);
		}
	}
	return command;
}
//end READ_COMMAND

//PRINT_MENU()
void print_menu(int menu_num)
{
	switch (menu_num){
	case MENU_MAIN:
		printf("MAIN MENU\n");
		printf("(c)onnect to server\n");
		printf("(q)uit\n");
		printf("=================\n");
		break;
	default:
		printf("Invalid menu number! ERROR! \n");
	}
}
//end PRINT_MENU()

//CONNECT_TO_SERVER()
int connect_to_server()
{
	SOCKET clientSock; //Used to talk with the server
	SOCKADDR_IN serverAddr; //Used for server's information
	int port = 8585; //random port, same as server's
	int ret;

	clientSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //default
	serverAddr.sin_family = AF_INET; //IPv4
	serverAddr.sin_port = htons(port);
	
	//TEST AREA: Will clean this up later with a real dialog with user input
	char ip_command = 'd'; //for default

	printf("Enter (d) for the default IP address (local host) or anything else for other comp.\n");
	ip_command = read_command();
	
	if ( ip_command != 'd' ){
		serverAddr.sin_addr.s_addr = inet_addr("192.168.167.44"); //Will eventually ask user for this
	}
	else{
		serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //Will eventually ask user for this
	}
	
	printf("Connecting to server...\n");
	ret = connect(clientSock, (SOCKADDR *) &serverAddr, sizeof(serverAddr));

	if ( ret != 0 ){
		printf("Error with connect! Error: %d\n", WSAGetLastError());
		return -1; //return with error
	}

	printf("Connected!\n");

	//Initialize for message loop
	char message[MESSAGE_SIZE] = "DEFAULT"; //Buffer for outgoing messages
	int messageLen = sizeof(message);
	int nLeft; //Used to keep track of bytes when using send()
	int idx; //Used to keep track of index when using send()
	char loopCommand = 'c';

	while ( loopCommand != 'q' ){
		//Get new message from user
		printf("Enter message to send to server.\n");
		fgets(message, MESSAGE_SIZE, stdin);

		nLeft = messageLen;
		idx = 0;

		//Send entire message
		while ( nLeft > 0 ){
			ret = send(clientSock, &message[idx], nLeft, 0);

			if ( ret == SOCKET_ERROR ){
				printf("Error with send! Error: %d\n", WSAGetLastError());
				return -1; //return with error
			}
			else if ( ret == 0 ){
				printf("Error! Socket already closed!\n");
			}
			else{
				nLeft -= ret;
				idx += ret;
			}
		}
		
		printf("Message sent!\n");

		//Ask user if they want to send another message
		printf("Do you want to send another message?\n");
		printf("Enter 'q' to quit, otherwise, enter any other char.\n");
		loopCommand = read_command();
	}

	//User is done sending messages so close socket
	shutdown(clientSock, SD_BOTH);
	closesocket(clientSock);

	printf("Finished sending messages.\n");

	return 0; //Return with success
}
//end CONNECT_TO_SERVER()